//
//  LFAlertBox.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/16.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "LFAlertBox.h"

static const CGFloat LFDefaultButtonFontSize  = 17;
static const CGFloat LFDefaultTitleFontSize   = 17;
static const CGFloat LFDefaultContentFontSize = 14;


@interface LFAlertBox ()

@property (nonatomic, strong) UIView *backgroundView;

@property (nonatomic, strong) UILabel *alertTitle;    // 标题
@property (nonatomic, strong) UILabel *alertContent;  // 内容
@property (nonatomic, strong) UILabel *verticalLine;  // 竖直线条

@property (nonatomic, strong) UIButton *cancleBtn;
@property (nonatomic, strong) UIButton *sureBtn;

@end

@implementation LFAlertBox


+ (instancetype)defaultAlert {
    static LFAlertBox *box = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        box = [[LFAlertBox alloc] init];
    });
    
    box.backgroundView.userInteractionEnabled = YES;

    return box;
}

+ (instancetype)backgroundAlert {
    LFAlertBox *box = [self defaultAlert];
    box.backgroundView.userInteractionEnabled = NO;
    return box;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self drawUI];
    }
    return self;
}

- (void)drawUI {
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius  = 5;
    self.layer.masksToBounds = YES;
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [window addSubview:_backgroundView];
    [window bringSubviewToFront:_backgroundView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popAction)];
    [_backgroundView addGestureRecognizer:tap];
    
    _alertTitle = [[UILabel alloc] init];
    _alertTitle.font = [UIFont boldSystemFontOfSize:LFDefaultTitleFontSize];
    _alertTitle.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_alertTitle];
    
    [_alertTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mas_top).offset(20);
        make.centerX.mas_equalTo(self.mas_centerX);
        make.height.mas_equalTo(20);
    }];
    
    
    UILabel *crossLine = [[UILabel alloc] init];
    crossLine.backgroundColor = KGMBACKGROUND_COLOR;
    [self addSubview:crossLine];
    
    [crossLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self);
        make.bottom.mas_equalTo(self.mas_bottom).offset(-42);
        make.height.mas_equalTo(0.6);
    }];
    
    _alertContent = [[UILabel alloc] init];
    _alertContent.textColor = KGMBLACK_COLOR;
    _alertContent.numberOfLines = 0;
    _alertContent.font = [UIFont systemFontOfSize:LFDefaultContentFontSize];
    _alertContent.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_alertContent];
    
    [_alertContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_alertTitle.mas_bottom).offset(15);
        make.bottom.mas_equalTo(crossLine.mas_top).offset(-25);
        make.leading.mas_equalTo(self.mas_leading).offset(20);
        make.trailing.mas_equalTo(self.mas_trailing).offset(-20);
    }];
    
    
    _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancleBtn.titleLabel.font = [UIFont systemFontOfSize:LFDefaultButtonFontSize];
    [_cancleBtn setTitleColor:KGMBLACK_COLOR forState:UIControlStateNormal];
    _cancleBtn.tag = 100;
    [_cancleBtn addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_cancleBtn];
    
    [_cancleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(crossLine.mas_bottom);
        make.leading.bottom.equalTo(self);
        make.width.mas_equalTo((KscreenWidth-100)/2);
    }];
    
    
    _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sureBtn.titleLabel.font = [UIFont systemFontOfSize:LFDefaultButtonFontSize];
    [_sureBtn setTitleColor:KGMBLACK_COLOR forState:UIControlStateNormal];
    _sureBtn.tag = 101;
    [_sureBtn addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_sureBtn];
    
    [_sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(crossLine.mas_bottom);
        make.trailing.bottom.equalTo(self);
        make.width.mas_equalTo((KscreenWidth-100)/2);
    }];
    
    _verticalLine = [[UILabel alloc] init];
    _verticalLine.backgroundColor = KGMBACKGROUND_COLOR;
    [self addSubview:_verticalLine];
    
    [_verticalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mas_centerX);
        make.top.mas_equalTo(crossLine.mas_bottom);
        make.bottom.mas_equalTo(self.mas_bottom);
        make.width.mas_equalTo(0.6);
    }];
    
    [window addSubview:self];
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(window);
        make.leading.mas_equalTo(window.mas_leading).offset(50);
        make.trailing.mas_equalTo(window.mas_trailing).offset(-50);
        make.bottom.mas_equalTo(_sureBtn.mas_bottom);
    }];
    
    self.alpha  = 0;
    self.hidden = YES;
    self.backgroundView.hidden = YES;
}

- (void)doAction:(UIButton *)sender {
    sender.enabled = NO;
    [self popAction];
    
    if (self.alertBlock) {
        self.alertBlock(sender.tag-100);
    }
    sender.enabled = YES;
}

- (void)show {
    WEAKSELF
    self.hidden = NO; self.ondisplay = YES;
    self.backgroundView.hidden = NO;
    [UIView animateWithDuration:0.4 animations:^{
        weakSelf.backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        weakSelf.alpha = 1;
    }];
}

- (void)popAction {
    WEAKSELF
    [UIView animateWithDuration:.4 animations:^{
        weakSelf.backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        weakSelf.alpha = 0;
    } completion:^(BOOL finished) {
        weakSelf.hidden = YES; weakSelf.ondisplay = NO;
        weakSelf.backgroundView.hidden = YES;
    }];
}


- (void)showAlert:(NSString *)content completion:(GRAlertBlock)completion {
    [self showAlertTitle:nil content:[self text:content isTheme:NO isContent:YES] cancleBtn:[self text:@"取消" isTheme:NO isContent:NO] sureBtn:[self text:@"确认" isTheme:NO isContent:NO] completion:^(NSInteger index) {
        if (completion) {
            completion(index);
        }
    }];
}

- (void)showAlertTitle:(NSString *)title content:(NSString *)content completion:(GRAlertBlock)completion {
    [self showAlertTitle:[self text:title isTheme:YES isContent:NO] content:[self text:content isTheme:NO isContent:YES] cancleBtn:[self text:@"取消" isTheme:NO isContent:NO] sureBtn:[self text:@"确定" isTheme:NO isContent:NO] completion:^(NSInteger index) {
        if (completion) {
            completion(index);
        }
    }];
}


- (void)showAlertContent:(NSString *)content cancle:(NSString *)cancle sure:(NSString *)sure completion:(GRAlertBlock)completion {
    [self showAlertTitle:nil content:[self text:content isTheme:NO isContent:YES] cancleBtn:(cancle ? [self text:cancle isTheme:NO isContent:NO] : nil) sureBtn:[self text:sure isTheme:NO isContent:NO] completion:^(NSInteger index) {
        if (completion) {
            completion(index);
        }
    }];
}

- (void)showAlertContent:(NSString *)content sure:(NSString *)sure completion:(GRAlertBlock)completion {
    [self showAlertTitle:nil content:[self text:content isTheme:NO isContent:YES] cancleBtn:nil sureBtn:[self text:sure isTheme:NO isContent:NO] completion:^(NSInteger index) {
        if (completion) {
            completion(index);
        }
    }];
}

- (void)showAlertTitle:(NSString *)title content:(NSString *)content cancleText:(NSString *)cancle sureText:(NSString *)sure completion:(GRAlertBlock)completion {
    [self showAlertTitle:(title ? [self text:title isTheme:YES isContent:NO] : nil) content:[self text:content isTheme:NO isContent:YES] cancleBtn:(cancle ? [self text:cancle isTheme:NO isContent:NO] : nil) sureBtn:[self text:sure isTheme:NO isContent:NO] completion:^(NSInteger index) {
        if (completion) {
            completion(index);
        }
    }];
}

- (NSDictionary *)text:(NSString *)text isTheme:(BOOL)isTheme isContent:(BOOL)isContent{
    UIColor *textColor = isTheme ? [UIColor blackColor] : KGMBLACK_COLOR;
    
    UIFont *font = [UIFont systemFontOfSize:LFDefaultButtonFontSize];
    if (isTheme) {
        font     = [UIFont boldSystemFontOfSize:LFDefaultTitleFontSize];
    }else if (isContent) {
        font     = [UIFont systemFontOfSize:LFDefaultContentFontSize];
    }
    
    NSDictionary *dic  = @{@"text"            : text,
                           @"textColor"       : textColor,
                           @"font"            : font,
                           @"backgroundColor" : [UIColor whiteColor],
                           };
    return dic;
}

/**
 统一处理
 */
- (void)showAlertTitle:(NSDictionary *)titleDic content:(NSDictionary *)contentDic cancleBtn:(NSDictionary *)cancleDic sureBtn:(NSDictionary *)sureDic completion:(GRAlertBlock)completion {
WEAKSELF
    if (titleDic) {
        if (self.alertTitle.hidden) {
            self.alertTitle.hidden = NO;
            [weakSelf.alertContent mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(weakSelf.alertTitle.mas_bottom).offset(15);
            }];
        }
        
        for (NSString *key in titleDic.allKeys) {
            [self configureProperty:key mappingValue:titleDic[key] Label:self.alertTitle];
        }
    }else {
        if (!self.alertTitle.hidden) {
            self.alertTitle.hidden = YES;
            [weakSelf.alertContent mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(weakSelf.alertTitle.mas_bottom).offset(-5);
            }];
        }
    }
    
    for (NSString *key in contentDic.allKeys) {
        [self configureProperty:key mappingValue:contentDic[key] Label:self.alertContent];
    }
    
    
    if (cancleDic) {
        if (self.cancleBtn.hidden) {
            self.cancleBtn.hidden = NO;
            [weakSelf.sureBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo((KscreenWidth-100)/2);
            }];
        }
        
        for (NSString *key in cancleDic.allKeys) {
            [self configureProperty:key mappingValue:cancleDic[key] Button:self.cancleBtn];
        }
        
    }else {
        
        _cancleBtn.hidden = YES;
        _verticalLine.hidden = YES;
        [weakSelf.sureBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(KscreenWidth-100);
        }];
        
    }
    
    for (NSString *key in sureDic.allKeys) {
        [self configureProperty:key mappingValue:sureDic[key] Button:self.sureBtn];
    }
    
    [self show];
    
    self.alertBlock = completion;
}


#pragma Mark  ===============  属性赋值  ===========================

- (void)configureProperty:(NSString *)property mappingValue:(id)value Button:(UIButton *)sender {
    if ([property isEqual:@"text"]) {
        [sender setTitle:value forState:UIControlStateNormal];
    }else if ([property isEqual:@"textColor"]) {
        [sender setTitleColor:value forState:UIControlStateNormal];
    }else if ([property isEqual:@"font"]) {
        sender.titleLabel.font = value;
    }else if ([property isEqual:@"backgroundColor"]) {
        sender.backgroundColor = value;
    }
}

- (void)configureProperty:(NSString *)property mappingValue:(id)value Label:(UILabel *)sender {
    if ([property isEqual:@"text"]) {
        sender.text      = value;
    }else if ([property isEqual:@"textColor"]) {
        sender.textColor = value;
    }else if ([property isEqual:@"font"]) {
        sender.font      = value;
    }else if ([property isEqual:@"backgroundColor"]) {
        sender.backgroundColor = value;
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
